<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Edit, Delete, Search, Refresh } from "@element-plus/icons-vue";
// 配置axios的基础URL为/api，利用vite代理解决跨域问题
import axios from "axios";
axios.defaults.baseURL = "/api";

// 搜索表单
const searchForm = reactive({
  name: "",
  status: "",
  phone: "",
  deptId: "",
});

// 部门和角色数据
const deptList = ref([]);
const roleList = ref([]);

// 表格数据
const tableData = ref([]);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 20,
});

// 对话框控制
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formData = reactive({
  id: "",
  username: "",
  name: "",
  phone: "",
  email: "",
  gender: 1,
  status: 1,
  deptId: "",
  roleId: "",
  image: "",
  remark: "",
});

// 重置表单
const resetForm = () => {
  // 重置搜索表单
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  // 重置编辑表单
  formData.id = "";
  formData.username = "";
  formData.name = "";
  formData.phone = "";
  formData.email = "";
  formData.gender = 1;
  formData.status = 1;
  formData.deptId = "";
  formData.roleId = "";
  formData.image = "";
  formData.remark = "";
  // 清空后自动查询列表
  queryUserList();
};

// 序号生成方法，从1开始
const indexMethod = (index) => {
  return (pagination.currentPage - 1) * pagination.pageSize + index + 1;
};

// 查询用户列表
const queryUserList = async () => {
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm,
    };

    // 移除空字符串参数
    Object.keys(params).forEach((key) => {
      if (params[key] === "") {
        delete params[key];
      }
    });

    const response = await axios.get("/users", { params });
    if (response.data.code === 1) {
      tableData.value = response.data.data.rows;
      pagination.total = response.data.data.total;
    } else {
      ElMessage.error(response.data.msg || "获取用户列表失败");
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  }
};

// 搜索
const search = () => {
  pagination.currentPage = 1;
  queryUserList();
};

// 新增用户
const addUser = () => {
  dialogTitle.value = "新增用户";
  formData.id = "";
  formData.username = "";
  formData.password = "";
  formData.name = "";
  formData.phone = "";
  formData.email = "";
  formData.gender = 1;
  formData.status = 1;
  formData.deptId = "";
  formData.roleId = "";
  formData.image = "";
  formData.remark = "";
  dialogVisible.value = true;
};

// 编辑用户
const editUser = async (row) => {
  try {
    dialogTitle.value = "编辑用户";
    // 根据接口文档，使用GET /users/{id}获取用户详情
    const response = await axios.get(`/users/${row.id}`);
    if (response.data.code === 1 && response.data.data) {
      // 填充表单数据，密码字段已从formData中移除
      const userData = response.data.data;
      // 确保不包含密码字段
      delete userData.password;
      Object.assign(formData, userData);
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.data.msg || "获取用户详情失败");
    }
  } catch (error) {
    console.error("获取用户详情失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  }
};

// 头像上传成功处理
const handleAvatarSuccess = (response) => {
  if (response.code === 1) {
    formData.image = response.data.url;
    ElMessage.success("头像上传成功");
  } else {
    ElMessage.error(response.msg || "头像上传失败");
  }
};

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("只支持 JPG/PNG 格式的图片");
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB");
  }
  return isJPG && isLt2M;
};

// 自定义上传方法
const customUpload = async (options) => {
  const { file, onSuccess, onError } = options;
  const formData = new FormData();
  formData.append("file", file);

  try {
    const response = await axios.post("/api/upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });
    onSuccess(response.data);
  } catch (error) {
    onError(error);
    ElMessage.error("上传失败，请稍后重试");
  }
};

// 删除用户
const deleteUser = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户「${row.name}」吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 根据接口文档，使用DELETE /users/{ids}删除用户
    const response = await axios.delete(`/users/${row.id}`);
    if (response.data.code === 1) {
      ElMessage.success("删除成功");
      queryUserList(); // 重新查询列表
    } else {
      ElMessage.error(response.data.msg || "删除失败");
    }
  } catch (error) {
    if (error.response) {
      // 接口返回错误，但不是用户取消
      if (error.response.data) {
        ElMessage.error(error.response.data.msg || "删除失败");
      }
    }
    // 用户取消删除不显示错误
  }
};

// 保存用户
const saveUser = async () => {
  if (!formData.name) {
    ElMessage.warning("请输入用户姓名");
    return;
  }
  if (!formData.username) {
    ElMessage.warning("请输入用户名");
    return;
  }

  try {
    if (formData.id) {
      // 编辑功能 - 实现PUT /users接口
      const response = await axios.put("/users", {
        id: formData.id,
        username: formData.username,
        name: formData.name,
        phone: formData.phone,
        email: formData.email,
        gender: formData.gender,
        status: formData.status,
        deptId: formData.deptId,
        roleId: formData.roleId,
        image: formData.image,
        remark: formData.remark,
      });
      if (response.data.code === 1) {
        ElMessage.success("编辑成功");
        dialogVisible.value = false;
        queryUserList(); // 重新查询列表
      } else {
        ElMessage.error(response.data.msg || "编辑失败");
      }
    } else {
      // 新增 - POST /users
      const response = await axios.post("/users", {
        username: formData.username,
        name: formData.name,
        phone: formData.phone,
        email: formData.email,
        gender: formData.gender,
        status: formData.status,
        deptId: formData.deptId,
        roleId: formData.roleId,
        image: formData.image,
        remark: formData.remark,
      });
      if (response.data.code === 1) {
        ElMessage.success("新增成功");
        dialogVisible.value = false;
        queryUserList(); // 重新查询列表
      } else {
        ElMessage.error(response.data.msg || "新增失败");
      }
    }
  } catch (error) {
    console.error("保存用户失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  }
};

// 查询所有用户列表
const queryAllUsers = async () => {
  try {
    const response = await axios.get("/users/list");
    if (response.data.code === 1) {
      // 这里可以将结果用于显示或其他操作
      console.log("所有用户数据:", response.data.data);
      return response.data.data;
    } else {
      ElMessage.error(response.data.msg || "获取所有用户失败");
      return [];
    }
  } catch (error) {
    console.error("获取所有用户失败:", error);
    ElMessage.error("网络错误，请稍后重试");
    return [];
  }
};

// 根据角色查询用户列表
const queryUsersByRole = async (roleLabel) => {
  try {
    const response = await axios.get(`/users/role/${roleLabel}`);
    if (response.data.code === 1) {
      // 这里可以将结果用于显示或其他操作
      console.log(`角色${roleLabel}的用户数据:`, response.data.data);
      return response.data.data;
    } else {
      ElMessage.error(response.data.msg || "根据角色查询用户失败");
      return [];
    }
  } catch (error) {
    console.error("根据角色查询用户失败:", error);
    ElMessage.error("网络错误，请稍后重试");
    return [];
  }
};

// 根据部门查询用户列表
const queryUsersByDept = async (deptId) => {
  try {
    const response = await axios.get(`/users/dept/${deptId}`);
    if (response.data.code === 1) {
      // 这里可以将结果用于显示或其他操作
      console.log(`部门${deptId}的用户数据:`, response.data.data);
      return response.data.data;
    } else {
      ElMessage.error(response.data.msg || "根据部门查询用户失败");
      return [];
    }
  } catch (error) {
    console.error("根据部门查询用户失败:", error);
    ElMessage.error("网络错误，请稍后重试");
    return [];
  }
};

// 分页处理
const handlePageChange = () => {
  queryUserList();
};

// 格式化性别显示
const formatGender = (gender) => {
  return gender === 1 ? "男" : "女";
};

// 格式化状态显示
const formatStatus = (status) => {
  return status === 1 ? "正常" : "停用";
};

// 格式化状态样式
const getStatusClass = (status) => {
  return status === 1 ? "status-normal" : "status-disabled";
};

// 格式化时间显示
const formatDateTime = (dateTime) => {
  if (!dateTime) return "";
  // 转换ISO格式时间为本地时间格式
  const date = new Date(dateTime);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 获取部门列表
const getDeptList = async () => {
  try {
    const response = await axios.get("/depts/list");
    if (response.data.code === 1) {
      deptList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || "获取部门列表失败");
    }
  } catch (error) {
    console.error("获取部门列表失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  }
};

// 获取角色列表
const getRoleList = async () => {
  try {
    const response = await axios.get("/roles/list");
    if (response.data.code === 1) {
      roleList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || "获取角色列表失败");
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
    ElMessage.error("网络错误，请稍后重试");
  }
};

// 组件挂载时加载数据
onMounted(async () => {
  // 并行加载部门和角色列表
  await Promise.all([getDeptList(), getRoleList()]);
  // 加载用户列表
  queryUserList();
});
</script>

<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="用户姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入用户姓名"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择"
            style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="searchForm.deptId"
            placeholder="请选择部门"
            style="width: 180px"
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="dept in deptList"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetForm">清空</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="addUser" style="margin-left: 10px">
        <el-icon><Plus /></el-icon>
        添加用户
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        type="index"
        :index="indexMethod"
        label="序号"
        width="80"
        align="center"
      />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column label="头像" width="100">
        <template #default="scope">
          <el-avatar
            :src="
              scope.row.image ||
              'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
            "
            size="small"
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="gender" label="性别" align="center">
        <template #default="scope">
          {{ formatGender(scope.row.gender) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <span :class="getStatusClass(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="deptName" label="部门" />
      <el-table-column prop="roleName" label="角色" />
      <el-table-column label="创建时间">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间">
        <template #default="scope">
          {{ formatDateTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editUser(scope.row)">
            <el-icon><Edit /></el-icon>
            修改
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteUser(scope.row)"
            style="margin-left: 10px"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handlePageChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="用户名" prop="username" :required="true">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="头像" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="'/api/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :model-value="formData.image"
            :http-request="customUpload"
          >
            <img v-if="formData.image" :src="formData.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="form-hint">支持 JPG、PNG 格式，大小不超过 2MB</div>
        </el-form-item>

        <el-form-item label="姓名" prop="name" :required="true">
          <el-input v-model="formData.name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" placeholder="请选择">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择">
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select
            v-model="formData.deptId"
            placeholder="请选择部门"
            style="width: 100%"
          >
            <el-option
              v-for="dept in deptList"
              :key="dept.id"
              :label="dept.name"
              :value="dept.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="formData.roleId"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            placeholder="请输入备注信息"
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.status-normal {
  color: #67c23a;
}

.status-disabled {
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.form-hint {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-uploader-icon {
  font-size: 20px;
  color: #c0c4cc;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
}

.avatar-uploader:hover .avatar-uploader-icon {
  color: #409eff;
  border-color: #409eff;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-container {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
